#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Purpose: 
# Created: 07/06/2009
# $Id $
# Copyright (c) 2008,2009 by University College London
# Authors:
#  --<>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.
"""
This plugin is intented to allow a user to export a selected network to be run 
with OpenIRAS
"""

import logging

from Thuban.UI.command import registry, Command
from Thuban.UI.mainwindow import main_menu 
from Thuban import _

from hydroplatform.ui.session import has_project
from hydroplatform.model.nodetypes import register_definition

from interface import IrasInterface
import definition


def get_iras_plugin_interface(context):
    """
    Returns the OpenIRAS plugin interface
    """
    networks = context.session.hpproject.networks
    netnames= [n.name for n in networks]
    print netnames
    iface = IrasInterface(networks=netnames, session = context.session)
    iface.edit_traits()
    
    
def enable_iras_project(context):
    dbsession = context.session.dbsession
    project= context.session.hpproject
    try:
        register_definition(dbsession, project, definition)
        nodeTypeMenu = context.application.get_nodetype_menu(context)
        nodeTypeMenu.cleanup()
        nodeTypeMenu.load_from_project(project)
        dbsession.commit()
    except Exception, e:
        logging.exception(e)
        dbsession.rollback()
        raise e
    

def isnot_iras_project(context):
    """
    Check if the selected project is not already an iras project
    """
    if has_project(context):
        # check node type names and link type names
        return not definition.is_iras_project(context.session.hpproject)
    else :
        return False
        
    

# locator executed as an tool/extension to Thuban
registry.Add(Command(name="run_iras_command", 
                     title="IRAS 2010 Exporter",
                     function=get_iras_plugin_interface,
                     sensitive = has_project,
                     helptext = "IRAS-2010 interface"))

registry.Add(Command(name="enable_iras_command", 
                     title="Add object types",
                     function=enable_iras_project,
                     sensitive = isnot_iras_project,
                     helptext = "Add the IRAS object types to your project"))



# find the extensions menu (create it anew if not found)
extensions_menu = main_menu.FindOrInsertMenu('hp_extensions', _('Add-ins'))
iras_menu = main_menu.FindOrInsertMenu('iras_extension', _('IRAS 2010'), ('hp_extensions',))

# finally add the new entry to the extensions menu
iras_menu.InsertItem('run_iras_command')
iras_menu.InsertItem('enable_iras_command')
